//
//  WPFirstTableHeaderView.m
//  wobingwoyi
//
//  Created by WGP on 16/11/8.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPFirstTableHeaderView.h"
#import "WPPickerView.h"
#import "WPMRModel.h"
#import "WPRecordEditeModel.h"
#import "YBPopupMenu.h"

@interface WPFirstTableHeaderView ()<UITextFieldDelegate,YBPopupMenuDelegate>

@property(nonatomic,strong)UILabel *firstLabel;
@property(nonatomic,strong)UIView *containerView;
@property(nonatomic,strong)UIImageView *imageView;
@property(nonatomic,strong)UILabel *label;

@property(nonatomic,strong)UILabel *diseaseLabel;
@property(nonatomic,strong)UILabel *doctorLabel;
@property(nonatomic,strong)UILabel *hospitalLabel;
@property(nonatomic,strong)UILabel *sexLabel;

@property(nonatomic,strong)UITextField *diseaseTextField;
@property(nonatomic,strong)UITextField *doctorTextField;
@property(nonatomic,strong)UITextField *treamentTextField;
@property(nonatomic,strong)UITextField *hospitalTextField;

@property(nonatomic,strong)UIButton *treamentStateBtn;
@property(nonatomic,strong)UIButton *ZXBtn;
@property(nonatomic,strong)UIImageView *treamentImageView;

@property(nonatomic,strong)UIButton *sexBtn;
@property(nonatomic,strong)UIButton *ageBtn;

@property(nonatomic,strong)NSArray *treamentArr;
@property(nonatomic,strong)NSArray *ZXArr;
@property(nonatomic,strong)NSArray *sexArr;
@property(nonatomic,strong)NSMutableArray *ageArr;
@property(nonatomic,strong)NSArray *departmentArr;

@property(nonatomic,strong)YBPopupMenu *ZXPopupMenu;

@end
@implementation WPFirstTableHeaderView

-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 231+44)])
    {
        [self setupUI];
        
        __weak typeof(self) weakSelf = self;
        [weakSelf setBaseInfoEditeBlock:^{
            
            [self showWithStatus:@"正在保存"];
            NSString *url = @"record/editRecord.do";
            
            WPRecordEditeModel *model = [WPRecordEditeModel new];
            model.name = weakSelf.diseaseTextField.text;
            model.cureStatus = weakSelf.treamentStateBtn.titleLabel.text;
            model.doctor = weakSelf.doctorTextField.text;
            model.hospital = weakSelf.hospitalTextField.text;
            model.sex = weakSelf.sexBtn.titleLabel.text;
            model.age = [weakSelf.ageBtn.titleLabel.text intValue];
            model.id = weakSelf.model.id;
            model.type = weakSelf.ZXBtn.titleLabel.text;
            
            NSString *JSONStr = [model yy_modelToJSONString];
            NSDictionary *dict = @{@"json":JSONStr};
            
            [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                
                [self dismiss];
                if ([responseObject[@"result"] isEqualToString:@"success"])
                {
                     [self showSuccessInfoWithStatus:@"保存成功"];
                    //保存成功后更新model
                    weakSelf.model.name = weakSelf.diseaseTextField.text;
                    weakSelf.model.cureStatus = weakSelf.treamentStateBtn.titleLabel.text;
                    weakSelf.model.doctor = weakSelf.doctorTextField.text;
                    weakSelf.model.hospital = weakSelf.hospitalTextField.text;
                    weakSelf.model.sex = weakSelf.sexBtn.titleLabel.text;
                    weakSelf.model.age = [weakSelf.ageBtn.titleLabel.text intValue];
                    weakSelf.model.type = weakSelf.ZXBtn.titleLabel.text;
                    
                    //保存成功后返回
                    if ([self.delegate respondsToSelector:@selector(WPFirstTableViewHeaderViewSaveSuccessBlock:)])
                    {
                        [self.delegate WPFirstTableViewHeaderViewSaveSuccessBlock:self];
                    }
                }
                else
                {
                    [self dismiss];
                    //            考虑到账号过期的情况
                    if ([responseObject[@"detail"] isEqualToString:@"illegalLogin"])
                    {
                        //                账号过期
                        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"账号过期,请重新登录" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                        [alertView show];
                    }
                    else
                    {
                        [self showErrorInfoWithStatus:responseObject[@"detail"]];
                    }
                }
                
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                
                [self dismiss];
                [self showErrorInfoWithStatus:@"网络错误"];
            }];

        }];
    }
    return self;
}

//重新登陆的代理方法
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0)
    {
         //账号过期,重新登录
    }
}

-(void)setupUI
{
    [self firstLabel];
    [self containerView];
    [self imageView];
    [self label];
}

-(UILabel *)firstLabel
{
    if (_firstLabel == nil)
    {
        _firstLabel = [UILabel new];
        _firstLabel.text = @"一诊诊断凭据";
        _firstLabel.textColor = GLobalFontColor;
        _firstLabel.textAlignment = NSTextAlignmentCenter;
        _firstLabel.font = [UIFont systemFontOfSize:15];
        _firstLabel.backgroundColor = [UIColor whiteColor];
        [self addSubview:_firstLabel];
        _firstLabel.frame = CGRectMake(0, 10, SCREEN_WIDTH, 44);
        
        UIImageView *line = [UIImageView lineImageView];
        [self addSubview:line];
        line.frame = CGRectMake(0, 10, SCREEN_WIDTH, 0.5);
    }
    return _firstLabel;
}

-(UIView *)containerView
{
    if (_containerView == nil)
    {
        _containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 54, SCREEN_WIDTH, 176)];
        _containerView.backgroundColor = [UIColor whiteColor];
        [self addSubview:_containerView];
        
        [self setupTreamentState];
        [self setLines];
        [self setupLabels];
        [self setupTextFields];
    }
    return _containerView;
}

-(UIImageView *)imageView
{
    if (_imageView == nil)
    {
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zhenduan"]];
        [self addSubview:_imageView];
        
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self).offset(10);
//            make.width.height.mas_equalTo(15);
            make.top.equalTo(self.containerView.mas_bottom).offset(15);
        }];
        
    }
    return _imageView;
}

-(void)setLines
{
    UIImageView *firstLine = [self lineView];
    UIImageView *secondLine = [self lineView];
    UIImageView *thirdLine = [self lineView];
    UIImageView *fourthLine = [self lineView];
    UIImageView *fifthLine = [self lineView];
    UIImageView *sixthLine = [self lineView];
    
    [_containerView addSubview:firstLine];
    [_containerView addSubview:secondLine];
    [_containerView addSubview:thirdLine];
    [_containerView addSubview:fourthLine];
    [_containerView addSubview:fifthLine];
    [_containerView addSubview:sixthLine];
    
    [firstLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(_containerView);
        make.height.mas_equalTo(0.5);
    }];
    
    [secondLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_containerView).offset(10);
        make.right.height.equalTo(firstLine);
        make.top.equalTo(_containerView).offset(44);
    }];
    
    [thirdLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(secondLine);
        make.top.equalTo(_containerView).offset(88);
    }];
    
    [fourthLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(secondLine);
        make.top.equalTo(_containerView).offset(132);
    }];
    
    [fifthLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.height.equalTo(firstLine);
        make.top.equalTo(_containerView).offset(176);
    }];
}

-(void)setupLabels
{
    UILabel *firstLabel = [self labelWith:@"疾病名称:"];
    self.diseaseLabel = firstLabel;
    UILabel *secondLabel = [self labelWith:@"诊治医生:"];
    self.doctorLabel = secondLabel;
    UILabel *fourthLabel = [self labelWith:@"治疗医院:"];
    self.hospitalLabel = fourthLabel;
    UILabel *fifthLabel = [self labelWith:@"患者性别:"];
    self.sexLabel = fifthLabel;
    UILabel *seventhLabel = [self labelWith:@"患者年龄:"];
    
    UIImageView *lineView = [UIImageView new];
    lineView.backgroundColor = GLobalLineColor;
    
    self.sexBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.ageBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.sexBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.ageBtn.titleLabel.font = [UIFont systemFontOfSize:15];
//    self.departmentBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [self.sexBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    [self.ageBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
//    [self.departmentBtn setTitleColor:[UIColor colorWithRed:0 green:0 blue:0.098 alpha:0.22] forState:UIControlStateNormal];
    
    [self.sexBtn setTitle:@"男" forState:UIControlStateNormal];
    [self.ageBtn setTitle:@"18" forState:UIControlStateNormal];
//    [self.departmentBtn setTitle:@"请输入治疗科室" forState:UIControlStateNormal];
    
    [self.sexBtn addTarget:self action:@selector(treamentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    [self.ageBtn addTarget:self action:@selector(treamentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
//    [self.departmentBtn addTarget:self action:@selector(treamentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    
    [_containerView addSubview:firstLabel];
    [_containerView addSubview:secondLabel];
//    [_containerView addSubview:thirdLabel];
    [_containerView addSubview:fourthLabel];
    [_containerView addSubview:fifthLabel];
    [_containerView addSubview:seventhLabel];
    [_containerView addSubview:lineView];
    [_containerView addSubview:self.sexBtn];
    [_containerView addSubview:self.ageBtn];
//    [_containerView addSubview:self.departmentBtn];
    
    CGSize size = [firstLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:15];
    CGFloat margin = (44-size.height)/2.0;
    
    [firstLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_containerView).offset(10);
        make.width.mas_equalTo(size.width+1);
        make.top.equalTo(_containerView).offset(margin);
    }];
    
    [secondLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(firstLabel);
        make.top.equalTo(firstLabel.mas_bottom).offset(2*margin);
    }];
    
//    [thirdLabel mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.width.equalTo(firstLabel);
//        make.top.equalTo(secondLabel.mas_bottom).offset(2*margin);
//    }];
    
    [fourthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(firstLabel);
        make.top.equalTo(secondLabel.mas_bottom).offset(2*margin);
    }];
    
    [fifthLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.width.equalTo(firstLabel);
        make.top.equalTo(fourthLabel.mas_bottom).offset(2*margin);
    }];
    
    [seventhLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.with.equalTo(fifthLabel);
        make.left.equalTo(_containerView.mas_centerX).offset(10);
    }];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(0.5);
        make.height.mas_equalTo(24);
        make.centerX.equalTo(_containerView.mas_centerX);
        make.centerY.equalTo(seventhLabel);
    }];
    
    [self.sexBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.sexLabel.mas_right).offset(5);
        make.right.equalTo(_containerView.mas_centerX).offset(-5);
        make.height.mas_equalTo(42);
        make.centerY.equalTo(self.sexLabel);
    }];
    
    [self.ageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(seventhLabel.mas_right).offset(5);
        make.right.equalTo(_containerView).offset(-5);
        make.height.equalTo(self.sexBtn);
        make.centerY.equalTo(seventhLabel);
    }];
}

-(void)setupTextFields
{
    self.diseaseTextField = [self textFieldWithPlaceholder:@"请输入疾病"];
    self.doctorTextField = [self textFieldWithPlaceholder:@"请输入诊治医生"];
    self.hospitalTextField = [self textFieldWithPlaceholder:@"请输入治疗医院"];
    
    self.diseaseTextField.delegate = self;
    self.doctorTextField.delegate = self;
    self.hospitalTextField.delegate = self;
    
    [_containerView addSubview:self.diseaseTextField];
    [_containerView addSubview:self.doctorTextField];
    [_containerView addSubview:self.hospitalTextField];
    
    [self.diseaseTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(42);
        make.centerY.equalTo(self.diseaseLabel);
        make.right.equalTo(self.ZXBtn.mas_left).offset(5);
        make.left.equalTo(self.diseaseLabel.mas_right).offset(8);
    }];
    
    [self.doctorTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.diseaseTextField);
        make.right.equalTo(_containerView).offset(-10);
        make.centerY.equalTo(self.doctorLabel);
    }];
    
    [self.hospitalTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.height.equalTo(self.diseaseTextField);
        make.right.equalTo(_containerView).offset(-10);
        make.centerY.equalTo(self.hospitalLabel);
    }];

}

-(void)setupTreamentState
{
    self.treamentStateBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.treamentStateBtn setTitle:@"治疗状态" forState:UIControlStateNormal];
    [self.treamentStateBtn setTitleColor:RGB_COLOR(208, 208, 213) forState:UIControlStateNormal];
    [_containerView addSubview:self.treamentStateBtn];
    [self.treamentStateBtn addTarget:self action:@selector(treamentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    self.treamentStateBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    
    CGSize size = [self.treamentStateBtn.titleLabel.text sizeWithMaxSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX) font:14];
    CGFloat margin = (44-size.height)/2.0;
    
    [self.treamentStateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(size.width+1);
        make.right.equalTo(_containerView).offset(-8);
        make.top.equalTo(_containerView).offset(margin);
        make.height.mas_equalTo(size.height);
    }];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"treamentState"]];
    self.treamentImageView = imageView;
    [_containerView addSubview:imageView];
    
    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.treamentStateBtn);
        make.right.equalTo(self.treamentStateBtn.mas_left).offset(-8);
        make.width.mas_equalTo(15);
        make.height.mas_equalTo(20);
    }];
    
    UIImageView *lineView = [[UIImageView alloc] init];
    lineView.backgroundColor = GLobalLineColor;
    [_containerView addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(0.5);
        make.height.mas_equalTo(24);
        make.centerY.equalTo(imageView);
        make.right.equalTo(imageView.mas_left).offset(-8);
    }];
    
    self.ZXBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.ZXBtn setBackgroundImage:[UIImage imageNamed:@"ZX_normal"] forState:UIControlStateNormal];
    [self.ZXBtn setBackgroundImage:[UIImage imageNamed:@"ZX_highlight"] forState:UIControlStateHighlighted];
    [self.ZXBtn setTitle:@"西医" forState:UIControlStateNormal];
    [self.ZXBtn setTitleColor:RGB_SAME(102) forState:UIControlStateNormal];
    self.ZXBtn .titleLabel.font = [UIFont systemFontOfSize:12];
    [self.ZXBtn addTarget:self action:@selector(treamentBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    [_containerView addSubview:self.ZXBtn];
    
    UIImage *image = [UIImage imageNamed:@"ZX_normal"];
    [self.ZXBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.treamentStateBtn);
        make.right.equalTo(lineView).offset(-10);
        make.width.mas_equalTo(image.size.width);
    }];
}

-(void)treamentBtnDidClick:(UIButton *)btn
{
    [self endEditing:YES];
    
    if (btn == self.treamentStateBtn)
    {
        
        CGSize size = [self.treamentArr[0] sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:14];
        YBPopupMenu *menu = [YBPopupMenu showRelyOnView:btn titles:self.treamentArr icons:nil menuWidth:size.width + 35 delegate:self];
        menu.fontSize = 14;
        menu.textColor = GLobalFontColor;
    }
    else if(btn == self.sexBtn)
    {
        WPPickerView *pickerView = [[WPPickerView alloc] initWithData:self.sexArr handleBlock:^(NSString *selectedData) {
            
            [self.sexBtn setTitle:selectedData forState:UIControlStateNormal];
            [self.sexBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        }];
        [pickerView show];
    }
    else if (btn == self.ageBtn)
    {
        WPPickerView *pickerView = [[WPPickerView alloc] initWithData:self.ageArr handleBlock:^(NSString *selectedData) {
            
            [self.ageBtn setTitle:selectedData forState:UIControlStateNormal];
            [self.ageBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
        }];
        [pickerView show];
    }
    else if(btn == self.ZXBtn)
    {
        CGSize size = [self.ZXArr[0] sizeWithMaxSize:CGSizeMake(MAXFLOAT, MAXFLOAT) font:14];
        self.ZXPopupMenu = [YBPopupMenu showRelyOnView:self.ZXBtn supView:self.containerView titles:self.ZXArr icons:nil menuWidth:size.width+35 delegate:self];
        self.ZXPopupMenu.fontSize = 14;
        self.ZXPopupMenu.textColor = GLobalFontColor;
    }

}

-(UILabel *)label
{
    if (_label == nil)
    {
        _label = [UILabel new];
        _label.font = [UIFont systemFontOfSize:15];
        _label.textColor = GLobalFontColor;
        _label.text = @"诊断单";
        [self addSubview:_label];
        
        [_label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self.imageView);
            make.left.equalTo(self.imageView.mas_right).offset(10);
        }];
    }
    return _label;
}

-(void)setModel:(WPMRModel *)model
{
    _model = model;
    self.diseaseTextField.text = model.name;
    
    if([self.model.cureStatus isEqualToString:@"未知"])
    {
        [self.treamentStateBtn setTitle:@"治疗状态" forState:UIControlStateNormal];
        [self.treamentStateBtn setTitleColor:RGB_COLOR(208, 208, 213) forState:UIControlStateNormal];
    }
    else
    {
        [self.treamentStateBtn setTitle:self.model.cureStatus forState:UIControlStateNormal];
        [self.treamentStateBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    }
    
    self.doctorTextField.text = model.doctor;
    self.hospitalTextField.text = model.hospital;
    [self.ZXBtn setTitle:model.type forState:UIControlStateNormal];
    
    [self.sexBtn setTitle:model.sex forState:UIControlStateNormal];
    [self.ageBtn setTitle:[NSString stringWithFormat:@"%zd",model.age] forState:UIControlStateNormal];
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == self.diseaseTextField)
    {
        self.model.name = textField.text;
    }
    else if (textField == self.doctorTextField)
    {
        self.model.doctor = textField.text;
    }
    else if(textField == self.hospitalTextField)
    {
        self.model.hospital = textField.text;
    }
    return YES;
}

-(UIImageView *)lineView
{
    UIImageView *lineView = [[UIImageView alloc] init];
    lineView.backgroundColor = GLobalLineColor;
    return lineView;
}

-(UILabel *)labelWith:(NSString *)title
{
    UILabel *label = [UILabel new];
    label.text = title;
    label.textColor = GLobalFontColor;
    label.font = [UIFont systemFontOfSize:15];
    return label;
}

-(UITextField *)textFieldWithPlaceholder:(NSString *)placeholder
{
    UITextField *field = [[UITextField alloc] init];
    field.placeholder = placeholder;
    field.font = [UIFont systemFontOfSize:15];
    field.textColor = GLobalFontColor;
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    return field;
}

#pragma mark - 弹出视图的代理方法
- (void)ybPopupMenuDidSelectedAtIndex:(NSInteger)index ybPopupMenu:(YBPopupMenu *)ybPopupMenu
{
    if (ybPopupMenu == self.ZXPopupMenu)
    {
        [self.ZXBtn setTitle:self.ZXArr[index] forState:UIControlStateNormal];
    }
    else
    {
        [self.treamentStateBtn setTitle:self.treamentArr[index] forState:UIControlStateNormal];
        [self.treamentStateBtn setTitleColor:GLobalFontColor forState:UIControlStateNormal];
    }
}

-(NSArray *)treamentArr
{
    if (_treamentArr == nil)
    {
        _treamentArr = [NSArray arrayWithObjects:@"未治愈",@"治疗中",@"已治愈", nil];
    }
    return _treamentArr;
}
-(NSArray *)ZXArr
{
    if (_ZXArr == nil)
    {
        _ZXArr = [NSArray arrayWithObjects:@"中医",@"西医", nil];
    }
    return _ZXArr;
}

-(NSArray *)sexArr
{
    if (_sexArr == nil)
    {
        _sexArr = [NSArray arrayWithObjects:@"男",@"女", nil];
    }
    return _sexArr;
}

-(NSMutableArray *)ageArr
{
    if (_ageArr == nil)
    {
        _ageArr = [NSMutableArray array];
        
        for (int i = 1; i <= 100; i++)
        {
            NSString *str = [NSString stringWithFormat:@"%zd",i];
            [_ageArr addObject:str];
        }
    }
    return _ageArr;
}

-(NSArray *)departmentArr
{
    if (_departmentArr == nil)
    {
        _departmentArr = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"departmentPlist.plist" ofType:nil]];
    }
    return _departmentArr;
}
@end
